<template>
	<view class="page-container">
		<cu-custom bgColor="bg-white" :isBack="true">
			<template #backText><text class="text-black">返回</text></template>
			<template #content><text class="text-black text-bold">账号与安全</text></template>
		</cu-custom>

		<view class="form-group">
            <view class="cu-form-group margin-top">
				<view class="title">用户名</view>
				<input placeholder="请输入用户名" v-model="form.username" />
			</view>
            <view class="cu-form-group">
                <view class="title">性别</view>
                <picker @change="onGenderChange" :value="genderIndex" :range="genderOptions">
                    <view class="picker">
                        {{genderOptions[genderIndex]}}
                    </view>
                </picker>
            </view>
        </view>

        <view class="form-group">
            <view class="cu-form-group margin-top">
				<view class="title">原密码</view>
				<input placeholder="请输入当前密码" v-model="form.currentPassword" type="password" />
			</view>
			<view class="cu-form-group">
				<view class="title">新密码</view>
				<input placeholder="请输入新密码" v-model="form.newPassword" type="password" />
			</view>
            <view class="cu-form-group">
				<view class="title">确认新密码</view>
				<input placeholder="请再次输入新密码" v-model="form.confirmPassword" type="password" />
			</view>
        </view>

		<view class="padding-xl">
			<button class="cu-btn block bg-gradual-blue lg" @click="handleSave" :loading="loading">
				{{ loading ? '保存中...' : '保存修改' }}
			</button>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { post } from '@/utils/request.js';

const form = ref({
    userId: null,
    username: '',
    gender: 0, // 0-保密, 1-男, 2-女
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
});

const genderOptions = ref(['保密', '男', '女']);
const genderIndex = ref(0);
const loading = ref(false);

onMounted(() => {
    const storedUser = uni.getStorageSync('user');
    if(storedUser) {
        try {
            const userInfo = JSON.parse(storedUser);
            form.value.userId = userInfo.userId;
            form.value.username = userInfo.userName;
            form.value.gender = userInfo.sex || 0;
            genderIndex.value = userInfo.sex || 0;
        } catch (e) {
            console.error("解析用户信息失败", e);
        }
    }
});

const onGenderChange = (e) => {
    genderIndex.value = e.detail.value;
    form.value.gender = parseInt(e.detail.value);
};

const handleSave = async () => {
    // 密码校验
    if(form.value.newPassword || form.value.currentPassword) {
        if(form.value.newPassword !== form.value.confirmPassword) {
            uni.showToast({ title: '两次输入的新密码不一致', icon: 'none'});
            return;
        }
        if(!form.value.currentPassword) {
            uni.showToast({ title: '请输入当前密码以修改密码', icon: 'none'});
            return;
        }
    }

    loading.value = true;
    try {
        const payload = {
            userId: form.value.userId,
            userName: form.value.username,
            sex: form.value.gender
        };

        // 如果填写了新密码，则一起提交
        if(form.value.newPassword) {
            payload.password = form.value.newPassword;
            payload.currentPassword = form.value.currentPassword; // 假设后端需要旧密码验证
        }
        
        // 实际应替换为您的后端接口
        const res = await post('/user/updateProfile', payload);

        if(res.data.code === 200) {
            uni.showToast({ title: '保存成功', icon: 'success' });
            // 更新本地存储的用户信息
            const storedUser = uni.getStorageSync('user');
            if(storedUser) {
                const userInfo = JSON.parse(storedUser);
                userInfo.userName = form.value.username;
                userInfo.sex = form.value.gender;
                uni.setStorageSync('user', JSON.stringify(userInfo));
            }
            setTimeout(() => uni.navigateBack(), 1500);
        } else {
            uni.showToast({ title: res.data.msg || '保存失败', icon: 'none' });
        }
    } catch(err) {
        console.error("保存失败", err);
        uni.showToast({ title: '网络错误，请稍后重试', icon: 'none' });
    } finally {
        loading.value = false;
    }
};

</script>

<style scoped>
.page-container {
	background-color: #f5f5f5;
	min-height: 100vh;
}
.text-black {
    color: #000000;
}
.form-group {
    margin-top: 20rpx;
}
</style> 